package com.xbongbong.paas.help.subform;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.help.subform.abstracts.AbstractUserTeamTransferSubForm;
import com.xbongbong.saas.domain.entity.UserTeamEntity;
import com.xbongbong.saas.enums.subform.DefaultTeamEnum;

/**
 * 默认用户团队es和数据库转化抽象类
 * @author zheng.li
 **/
public class DefaultUserTeamTransferSubForm extends AbstractUserTeamTransferSubForm {


    @Override
    public PaasFormDataEntity transferTeamToFormData(UserTeamEntity userTeamEntity) {
        PaasFormDataEntity paasFormDataEntity = createPaasFormDataEntityForUserTeam(userTeamEntity);

        JSONObject teamJson = JSONObject.parseObject(JSON.toJSONString(userTeamEntity));

        JSONObject data = new JSONObject();

        DefaultTeamEnum[] defaultTeamEnums = DefaultTeamEnum.values();
        for (DefaultTeamEnum anEnum : defaultTeamEnums) {
            String dbAttr = anEnum.getDbAttr();
            String dataAttr = anEnum.getDataAttr();
            Integer fieldType = anEnum.getFieldType();
            formatDataForEs(teamJson, data, dbAttr, dataAttr, fieldType);
        }
        paasFormDataEntity.setData(data);
        return paasFormDataEntity;
    }

    @Override
    public UserTeamEntity transferFormDataToTeam(PaasFormDataEntity paasFormDataEntity) {
        JSONObject data = paasFormDataEntity.getData();

        JSONObject dbData = new JSONObject();
        DefaultTeamEnum[] defaultTeamEnums = DefaultTeamEnum.values();
        for (DefaultTeamEnum anEnum : defaultTeamEnums) {
            String dbAttr = anEnum.getDbAttr();
            String dataAttr = anEnum.getDataAttr();
            Integer fieldType = anEnum.getFieldType();
            formatDataForDb(data, dbData, dbAttr, dataAttr, fieldType);

        }
        UserTeamEntity userTeamEntity = JSON.parseObject(dbData.toJSONString(), UserTeamEntity.class);
        userTeamEntity.setAddTime(paasFormDataEntity.getAddTime());
        userTeamEntity.setUpdateTime(paasFormDataEntity.getUpdateTime());
        userTeamEntity.setCorpid(paasFormDataEntity.getCorpid());
        userTeamEntity.setDel(paasFormDataEntity.getDel());
        userTeamEntity.setId(paasFormDataEntity.getId());

        return userTeamEntity;
    }

}
